package com.example.flex.utils.db;

import com.example.flex.domain.generator.DataBaseEntity;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author: 不是菜鸡爱编程
 * @Date: 2023/10/25
 * @Description：
 */
public class DataBaseUtil {
    /**
     * url前缀
     */
    private static final StringBuilder URL_PREFIX = new StringBuilder("jdbc:mysql://");
    /**
     * url端口
     */
    private static final StringBuilder URL_PORT = new StringBuilder(":3306/");
    /**
     * url后缀
     */
    private static final StringBuilder URL_SUFFIX = new StringBuilder("?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8");
    private static Connection connection;

    public static Connection initDataBase(DataBaseEntity dataBase) {
        String url = URL_PREFIX + dataBase.getIp() + URL_PORT + dataBase.getDataBaseName() + URL_SUFFIX;
        try {
            if (connection != null) {
                connection.close();
            }
            connection=getConnection(dataBase, url);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


    /**
     * 获得连接
     *
     * @return {@link Connection}
     */
    public static Connection getConnection() {
        return connection;
    }

    /**
     * 获得连接
     *
     * @param dataBase 数据库
     * @param url      url
     */
    private static Connection getConnection(DataBaseEntity dataBase, String url) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, dataBase.getUsername(), dataBase.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            connection=null;
            e.printStackTrace();
        }
        return connection;
    }
}
